package com.bz.xtcx.manager.service.impl;

import com.bz.xtcx.manager.service.IEmailService;
import com.bz.xtcx.manager.utils.WzStrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;

@Service
public class EmailService implements IEmailService{

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;//spring 提供的邮件发送类

    @Value("${mail.fromMail.addr}")
    private String from;

    @Value("${mail.fromMail.addr-alias}")
    private String fromAlias;

    @Override
	public boolean sendRegisterEmailHtml(String to, String uuid) {
        String subject = "苏南自创区国家军民科技协同创新平台会员电子邮件地址确认";
        StringBuilder  content = new StringBuilder();
        content.append("苏南自创区国家军民科技协同创新平台会员电子邮件地址确认").append("<br>").append("尊敬的会员:<br>");
        content.append("您的账号为您的注册邮箱，为了确保您的电子邮件地址可以成功的接收到平台发出的电子邮件，请点击以下地址    ");
        content.append(uuid);
        content.append("  进行确认。如果您在电子邮件中无法点击此地址，请将此地址复制到浏览器的地址栏中并回车确认。<br>此邮件无需回复，如需与平台联系，请发送邮件到邮件到jspc5979@126.com或拔打服或拔打服务热线025-8485913。");
		MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息
        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                helper.setFrom(new InternetAddress(addrNick + " <" + from + ">"));
            } else {
                helper.setFrom(from);
            }
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content.toString(), true);
            mailSender.send(message);
            return true;
        } catch (MessagingException e) {
            logger.error("发送注册激活邮件时发生异常！", e);
        } catch (Exception e) {
            logger.error("发送注册激活邮件时发生系统异常！", e);
        }
        return false;
	}
    
    @Override
	public boolean sendRegisterEmail(String to, String uuid) {
        String subject = "协同创新平台注册";
        StringBuilder  content = new StringBuilder();
        content.append("苏南自创区国家军民科技协同创新平台会员验证码：").append("<br>");
        content.append(uuid);
        content.append("<br>").append("请尽快验证过且不要泄露给他人");
        try {
            SimpleMailMessage message = new SimpleMailMessage();//创建简单邮件消息
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                message.setFrom(addrNick + " <" + from + ">");
            } else {
                message.setFrom(from);
            }
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content.toString());

            mailSender.send(message);
            return true;
        } catch (Exception e) {
            logger.error("发送注册激活邮件时发生异常！", e);
        }
		return false;
	}
    
    @Override
	public boolean sendCodeEmail(String to, String uuid) {
        String subject = "协同创新平台验证码";
        StringBuilder  content = new StringBuilder();
        content.append("苏南自创区国家军民科技协同创新平台会员验证码：").append("\r\n");
        content.append(uuid);
        content.append("\r\n").append("请尽快验证过且不要泄露给他人");
        SimpleMailMessage message = new SimpleMailMessage();//创建简单邮件消息
        //设置发送人
        String addrNick = checkFromAlias();
        if (WzStrUtil.isNotBlank(addrNick)) {
            message.setFrom(addrNick + " <" + from + ">");
        } else {
            message.setFrom(from);
        }
        message.setTo(to);//设置收件人
        message.setSubject(subject);//设置主题
        message.setText(content.toString());//设置内容
        try {
            mailSender.send(message);//执行发送邮件
            logger.info("简单邮件已经发送。");
            return true;
        } catch (Exception e) {
            logger.error("发送简单邮件时发生系统异常！", e);
        }
		return false;
	}
    
    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();//创建简单邮件消息
        //设置发送人
        String addrNick = checkFromAlias();
        if (WzStrUtil.isNotBlank(addrNick)) {
            message.setFrom(addrNick + " <" + from + ">");
        } else {
            message.setFrom(from);
        }
        message.setTo(to);//设置收件人
        message.setSubject("xx");
        message.setText("test mail");

        /* String[] adds = {"xxx@qq.com","yyy@qq.com"}; //同时发送给多人
        message.setTo(adds);*/

        
        try {
            mailSender.send(message);//执行发送邮件
            logger.info("简单邮件已经发送。");
        }catch (Exception e) {
            logger.error("发送简单邮件时发生系统异常！", e);
        }
    }

    @Override
    public void sendHtmlEmail(String to, String subject, String content) {
        MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息

        try {
            //true表示需要创建一个multipart message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                helper.setFrom(new InternetAddress(addrNick + " <" + from + ">"));
            } else {
                helper.setFrom(from);
            }
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            mailSender.send(message);
            logger.info("html邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送html邮件时发生异常！", e);
        } catch (Exception e) {
            logger.error("发送html邮件时发生系统异常！", e);
        }
    }

    @Override
    public void sendAttachmentsEmail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.createMimeMessage();//创建一个MINE消息

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                helper.setFrom(new InternetAddress(addrNick + " <" + from + ">"));
            } else {
                helper.setFrom(from);
            }
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);// true表示这个邮件是有附件的

            FileSystemResource file = new FileSystemResource(new File(filePath));//创建文件系统资源
            String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
            helper.addAttachment(fileName, file);//添加附件

            mailSender.send(message);
            logger.info("带附件的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送带附件的邮件时发生异常！", e);
        } catch (Exception e) {
            logger.error("发送带附件的邮件时发生系统异常！", e);
        }
    }

    @Override
    public void sendInlineResourceEmail(String to, String subject, String content, String rscPath, String rscId) {
        MimeMessage message = mailSender.createMimeMessage();

        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                helper.setFrom(new InternetAddress(addrNick + " <" + from + ">"));
            } else {
                helper.setFrom(from);
            }
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);

            FileSystemResource res = new FileSystemResource(new File(rscPath));

            //添加内联资源，一个id对应一个资源，最终通过id来找到该资源
            helper.addInline(rscId, res);//添加多个图片可以使用多条 <img src='cid:" + rscId + "' > 和 helper.addInline(rscId, res) 来实现

            mailSender.send(message);
            logger.info("嵌入静态资源的邮件已经发送。");
        } catch (MessagingException e) {
            logger.error("发送嵌入静态资源的邮件时发生异常！", e);
        } catch (Exception e) {
            logger.error("发送嵌入静态资源的邮件时发生系统异常！", e);
        }
    }

    /**
     * 检查发送人别名.
     * @return 别名
     */
    private String checkFromAlias() {
        String ank = fromAlias;
        if (WzStrUtil.isNotBlank(ank)) {
            try {
                ank = MimeUtility.encodeText(ank);
            } catch (Exception ex) {
                logger.error("邮件发送地址昵称转换失败", ex);
                ank = null;
            }
        }
        return ank;
    }
}
